# 导入flask
from flask import Blueprint,request,jsonify


# 密码加密
from werkzeug.security import generate_password_hash,check_password_hash


from conf.comm import sqlalchemy_context

from database import *

# 引入json
import json
import re


#蓝图初始化
bp_users = Blueprint('users',__name__)
#注册功能实现
@bp_users.route('/reg',methods = ['POST'])
@sqlalchemy_context()
def reg():
    # 获取用户输入
    data = request.data
    if not data:
        data = request.form
    else:
        data = json.loads(data)

    # 有效性验证 使用正则验证手机号
    reg = re.match('^1[3-9][0-9]{9}$',data['mobile'])
    if not reg:
        return jsonify({"code":10012,'mes':'手机号不合法'}) 
    # 构造user
    try:
        user = User(username = data['username'],
                  password = generate_password_hash(data['password']),
                  mobile = data['mobile'])
        db.session.add(user)
        db.session.commit()
        return jsonify({'code':200})

    except:
        return jsonify({'code':10010})